package com.example.project.utils;


import com.alibaba.fastjson.JSON;
import com.example.project.vo.model.AuthUser;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;

/**
 * jwt工具类
 *
 * @author zed
 * @date 2022/12/06
 */
public class JwtUtils {

    public static final String JWT_KEY = "authUer";
    // 加盐
    public static final String SALT = "com.exapmple";


    /**
     *
     * @param
     * @return
     */
    public static String createToken(AuthUser authUser) {
        String jsonAuthUser = JSON.toJSONString(authUser);

        //创建JWT对象
        JwtBuilder builder = Jwts.builder()//设置负载内容
                .setSubject("SUSE")
                .setId(jsonAuthUser)// 添加自定义声明
                .setIssuedAt(new Date())//设置签发时间
                .signWith(SignatureAlgorithm.HS256, SALT)

                ;//设置签名秘钥
        //构建token
        String compact = builder.compact();
        return compact;
    }


    public static AuthUser parseToken(String token) {
        Claims claims = Jwts.parser().setSigningKey(SALT).parseClaimsJws(token).getBody();
        String jsonAuthUser = claims.getId();
        AuthUser authUser = JSON.parseObject(jsonAuthUser, AuthUser.class);
        return authUser;
    }


}
